#pragma once

#include <iostream>
#include <cstring>
#include <algorithm>
#include <assert.h>

using namespace std;

template<class K, class V>
struct AVLTreeNode {
	pair<K, V> _kv;
	AVLTreeNode<K, V>* _left;
	AVLTreeNode<K, V>* _right;
	AVLTreeNode<K, V>* _parent;
	int _bf;						// balance factor

	AVLTreeNode(const pair<K, V>& kv)
		:_kv(kv)
		, _left(nullptr)
		, _right(nullptr)
		, _parent(nullptr)
		, _bf(0)
	{}
};

template<class K, class V>
class AVLTree {
	typedef AVLTreeNode<K, V> Node;
public:
	AVLTree() = default;

	AVLTree(const AVLTree<K, V>& t)
	{
		_root = Copy(t._root);
	}

	AVLTree<K, V>& operator=(AVLTree<K, V> t)
	{
		swap(_root, t._root);
		return *this;
	}

	~AVLTree()
	{
		Destroy(_root);
		_root = nullptr;
	}


	bool Insert(const pair<K, V>& kv)
	{
		if (_root == nullptr) {
			_root = new Node(kv);
			return true;
		}

		Node* cur = _root, *parent = nullptr;
		while (cur)
		{
			if (cur->_kv.first == kv.first) return false;
			else if (cur->_kv.first < kv.first) {
				parent = cur;
				cur = cur->_right;
			}
			else {
				parent = cur;
				cur = cur->_left;
			}
		}
		cur = new Node(kv);
		if (kv.first > parent->_kv.first) parent->_right = cur;
		else parent->_left = cur;

		cur->_parent = parent;										// 链接父亲

		//更新平衡因子
		while (parent)
		{
			if (cur == parent->_left) parent->_bf--;
			else parent->_bf++;

			if (parent->_bf == 0) break;
			else if (parent->_bf == -1 || parent->_bf == 1)
			{
				cur = parent;
				parent = parent->_parent;
			}
			else if (parent->_bf == -2 || parent->_bf == 2)
			{
				// 不平衡了，旋转处理
				if (parent->_bf == 2 && cur->_bf == 1)         // 全是在右边插入的 只需要右单旋即可
				{
					RotateL(parent);
				}
				else if (parent->_bf == -2 && cur->_bf == -1)  // 全是在左边插入的 只需要左单旋即可
				{
					RotateR(parent);
				}
				else if (parent->_bf == 2 && cur->_bf == -1)   // 先右旋再左旋  （右边高，孩子左边高， 父子异号）
				{
					RotateRL(parent);
				}
				else
				{
					RotateLR(parent);						   //  先左旋再右旋  （左边高，孩子右边高， 父子异号）
				}

				break;
			}
			else {
				assert(false);
			}
		}

		return true;
	}


	Node* Find(K& key)
	{
		if (_root == nullptr) return false;
		Node* cur = _root;

		while (cur)
		{
			if (cur->_kv.first == key) return cur;
			else if (cur->_kv.first < key) cur = cur->_right;
			else cur = cur->_left;
		}
		return nullptr;
	}

	bool Erase(const K& key)
	{
		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				// 删除
				// 0-1个孩子的情况
				if (cur->_left == nullptr)
				{
					if (parent == nullptr)
					{
						_root = cur->_right;
					}
					else
					{
						if (parent->_left == cur)
							parent->_left = cur->_right;
						else
							parent->_right = cur->_right;
					}

					delete cur;
					return true;
				}
				else if (cur->_right == nullptr)
				{
					if (parent == nullptr)
					{
						_root = cur->_left;
					}
					else
					{
						if (parent->_left == cur)
							parent->_left = cur->_left;
						else
							parent->_right = cur->_left;
					}

					delete cur;
					return true;
				}
				else
				{
					// 2个孩子的情况
					// 右子树的最小节点作为替代节点
					Node* rightMinP = cur;
					Node* rightMin = cur->_right;
					while (rightMin->_left)
					{
						rightMinP = rightMin;
						rightMin = rightMin->_left;
					}

					cur->_key = rightMin->_key;

					if (rightMinP->_left == rightMin)
						rightMinP->_left = rightMin->_right;
					else
						rightMinP->_right = rightMin->_right;

					delete rightMin;
					return true;
				}
			}
		}

		return false;
	}

	Node* Copy(Node* root)
	{
		if (root == nullptr)
			return nullptr;

		Node* newRoot = new Node(root->_kv);
		newRoot->_left = Copy(root->_left);
		newRoot->_right = Copy(root->_right);

		return newRoot;
	}

	void Destroy(Node* root)
	{
		if (root == nullptr)
			return;

		Destroy(root->_left);
		Destroy(root->_right);
		delete root;
	}

	void InOrder()
	{
		_InOrder(_root);
	}

private:
	// 第一种情况 : 左单旋   (插入在最右边)
	void RotateL(Node* parent)
	{
		Node* subR = parent->_right;
		Node* subRL = subR->_left;

		parent->_right = subRL;
		if (subRL) subRL->_parent = parent;

		Node* parent_parent = parent->_parent;

		subR->_left = parent;
		parent->_parent = subR;

		if (parent_parent == nullptr)
		{
			_root = subR;
			subR->_parent = nullptr;
		}
		else {
			if (parent == parent_parent->_left) parent_parent->_left = subR;
			else parent_parent->_right = subR;

			subR->_parent = parent_parent;
		}

		parent->_bf = subR->_bf = 0;		// 维护平衡因子
	}

	// 第二种情况 : 右单旋   （插入在最左边）
	void RotateR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = parent->_left->_right;

		parent->_left = subLR;
		if (subLR) subLR->_parent = parent;


		Node* parent_parent = parent->_parent;

		subL->_right = parent;
		parent->_parent = subL;


		if (parent_parent == nullptr)
		{
			_root = subL;
			subL->_parent = nullptr;
		}
		else {
			if (parent == parent_parent->_left)
			{
				parent_parent->_left = subL;
			}
			else {
				parent_parent->_right = subL;
			}
			subL->_parent = parent_parent;

		}
		parent->_bf = subL->_bf = 0;        // 维护平衡因子
	}

	//第三种情况 : 先右旋再左旋  （右边高，孩子左边高， 父子异号）
	void RotateRL(Node* parent)
	{
		//先记录下来，才能更新平衡因子
		Node* subR = parent->_right;
		Node* subRL = subR->_left;
		int bf = subRL->_bf;            // 判断的关键    判断是新插入还是左边还是右边插入的

		RotateR(parent->_right);
		RotateL(parent);

		if (bf == 0)      // 这种情况就是单独新插入了一个节点 其实我觉得这一步本来就是没必要置为0了
		{
			subR->_bf = 0;
			subRL->_bf = 0;
			parent->_bf = 0;
		}
		else if (bf == 1)
		{
			subR->_bf = 0;
			subRL->_bf = 0;
			parent->_bf = -1;
		}
		else if (bf == -1)
		{
			subR->_bf = 1;
			subRL->_bf = 0;
			parent->_bf = 0;
		}
		else
		{
			assert(false);
		}
	}

	//第四种情况 : 先左旋再右旋  （左边高，孩子右边高， 父子异号）
	void RotateLR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;
		int bf = subLR->_bf;

		RotateL(subL);
		RotateR(parent);

		if (bf == 0)
		{
			parent->_bf = 0;
			subL->_bf = 0;
			subLR->_bf = 0;
		}
		else if (bf == 1)
		{
			subL->_bf = -1;
			subLR->_bf = 0;
			parent->_bf = 0;
		}
		else if (bf == -1)
		{
			subL->_bf = 0;
			subLR->_bf = 0;
			parent->_bf = 1;
		}
		else{
			assert(false);
		}
	}

	void _InOrder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}

		_InOrder(root->_left);
		cout << root->_kv.first << ":" << root->_kv.second <<  " " << root->_bf << endl;
		_InOrder(root->_right);
	}


	Node* _root = nullptr;
};

void TestAVLTree()
{
	AVLTree<int, int> t;
	int a[] = { 16, 3, 7, 11, 9, 26, 18, 14, 15};

	for (auto e : a)
	{
		t.Insert({ e, e });
	}

	t.InOrder();
}


// 数据生成最后的树 11(7(3, 11), 18(15(14, 16), 26))